import { useState } from 'react';
import { Button, Modal, Input, Flex, message, ConfigProvider } from 'antd';
import { TeamOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { verifyDocShareCode } from '../api';
import style from './JoinCollaborationBtn.module.less';

const JoinCollaborationBtn = () => {
    const [joinModalOpen, setJoinModalOpen] = useState(false);
    const [joinCode, setJoinCode] = useState('');
    const [joinLoading, setJoinLoading] = useState(false);
    const navigate = useNavigate();

    const handleJoinCollaboration = async () => {
        if (!joinCode.trim()) {
            message.error('请输入分享码！');
            return;
        }
        setJoinLoading(true);
        try {
            const res = await verifyDocShareCode(joinCode.trim());
            if (res && res.code === 200 && res.data) {
                message.success('成功加入协作！');
                setJoinCode('');
                setJoinModalOpen(false);
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
                // 延迟跳转以确保页面刷新完成
                setTimeout(() => {
                    navigate(`/docList/docDetail/${res.data.docId}`, {
                        state: {
                            docName: res.data.docName,
                            docContent: typeof res.data.docContent === 'string'
                                ? JSON.parse(res.data.docContent)
                                : res.data.docContent,
                                docPermission: res.data.docPermission,
                                isJoinedViaShareCode: true
                        }
                    });
                }, 100);
            } else {
                message.error(res?.msg || '加入协作失败');
            }
        } catch (err) {
            message.error('加入协作失败，请检查分享码是否正确');
        } finally {
            setJoinLoading(false);
        }
    };

    return (
        <>
            <Button
                className={style.box}
                type="default"
                style={{ padding: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
                onClick={() => setJoinModalOpen(true)}
            >
                <span className={style.firIcon} style={{ marginRight: 8 }}>
                    <TeamOutlined />
                </span>
                <span className={style.text}>加入协作</span>
            </Button>
            <Modal
                title="加入协作"
                open={joinModalOpen}
                onCancel={() => setJoinModalOpen(false)}
                footer={null}
                width={400}
                centered
            >
                <div style={{ padding: '20px 0' }}>
                    <div style={{ marginBottom: '12px' }}>
                        <label style={{ display: 'block', marginBottom: 8, fontWeight: 500, color: '#333' }}>
                            分享码：
                        </label>
                        <Input
                            placeholder="请输入分享码"
                            value={joinCode}
                            onChange={e => setJoinCode(e.target.value)}
                            onPressEnter={handleJoinCollaboration}
                            autoFocus
                        />
                    </div>
                    <Flex gap="small" wrap>
                        <Button
                            type="primary"
                            style={{ width: '100%' }}
                            onClick={handleJoinCollaboration}
                            loading={joinLoading}
                        >
                            确定加入
                        </Button>
                    </Flex>
                </div>
            </Modal>
        </>
    );
};

export default JoinCollaborationBtn;
